import * as c from 'colors'
import { createConnection } from 'typeorm'
import { connectionOptions } from '../../scretConfig'
import { Server } from '../../server'
import { BaseService } from '../BaseService'
import { StudentService } from './StudentService'
import { SubjectService } from './SubjectService'

export class MysqlService extends BaseService {
  public studentService!: StudentService
  public subjectService!: SubjectService
  constructor(server: Server) {
    super(server)
    this.init()
  }

  private init() {
    this.createConnectionForMysql().then(() => {
      this.studentService = new StudentService(this)
      this.subjectService = new SubjectService(this)
    }).catch((err) => {
      console.error(err)
      console.log(c.red('[ 数据库连接失败 ]'))
    })
  }

  private async createConnectionForMysql() {
    return await createConnection({
      ...connectionOptions,
      type: 'mysql',
      // 这个选项可以在应用启动时， 确保实体和数据库保持同步
      // synchronize: process.env.NODE_ENV === 'production' ? false : true,
      logging: true,
    })
  }

}
